<template>
  <div class="main">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd">
              <IconifyIconOffline icon="ep:plus" />
              新增角色
            </el-button>
            <el-button @click="handleRefresh">
              <IconifyIconOffline icon="ep:refresh" />
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <div class="content">
        <!-- 搜索区域 -->
        <div class="search-container">
          <el-form :model="searchForm" inline>
            <el-form-item label="角色名称">
              <el-input
                v-model="searchForm.name"
                placeholder="请输入角色名称"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <IconifyIconOffline icon="ep:search" />
                搜索
              </el-button>
              <el-button @click="handleReset">
                <IconifyIconOffline icon="ep:refresh-left" />
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 角色列表表格 -->
        <el-table
          v-loading="loading"
          :data="roleList"
          border
          stripe
          style="width: 100%"
        >
          <el-table-column prop="id" label="ID" width="80" />

          <el-table-column prop="name" label="角色名称" min-width="150" />

          <el-table-column prop="pname" label="权限名称" min-width="200">
            <template #default="{ row }">
              <el-tag v-if="row.pname" type="info" size="small">
                {{ row.pname }}
              </el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>

          <el-table-column prop="description" label="描述" min-width="100">
            <template #default="{ row }">
              <span>{{ row.description || "-" }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间" min-width="180">
            <template #default="{ row }">
              <span>{{ formatDate(row.createTime) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="300" fixed="right">
            <template #default="{ row }">
              <el-button type="success" size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                删除
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="openPermissionDialog(row)"
              >
                更改权限
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.limit"
            :page-sizes="[5, 10, 20, 50]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入角色名称" />
        </el-form-item>

        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          :loading="submitLoading"
          type="primary"
          @click="handleSubmit"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 新增权限对话框 -->
    <el-dialog
      v-model="permsDialogVisible"
      title="新增权限"
      width="600px"
      :close-on-click-modal="false"
    >
      <div style="margin-bottom: 10px">请选择需要授予给该角色的权限：</div>
      <el-tree
        ref="permTreeRef"
        v-loading="permsLoading"
        :data="permissionTree"
        node-key="id"
        show-checkbox
        default-expand-all
        :props="{ children: 'children', label: 'name' }"
        style="max-height: 50vh; overflow: auto"
      >
        <template #default="{ data }">
          <span>
            {{ data.name }}
            <span v-if="data.perms" style="margin-left: 6px; color: #909399"
              >({{ data.perms }})</span
            >
          </span>
        </template>
      </el-tree>
      <template #footer>
        <el-button @click="permsDialogVisible = false">取消</el-button>
        <el-button
          :loading="permsSubmitLoading"
          type="primary"
          @click="submitPermissions"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  getRoleList,
  createRole,
  updateRole,
  deleteRole,
  type RoleItem
} from "@/api/role";
import {
  updateRolePermission,
  type UpdateRolePermissionParams,
  findPermissionByUserId
} from "@/api/role";
import { getMenuTree, type MenuItem } from "@/api/menu";

defineOptions({
  name: "SystemRole"
});

// 响应式数据
const loading = ref(false);
const roleList = ref<RoleItem[]>([]);
const dialogVisible = ref(false);
const submitLoading = ref(false);
const isEdit = ref(false);
const currentEditId = ref<number | null>(null);

// 新增权限对话框相关
const permsDialogVisible = ref(false);
const permsLoading = ref(false);
const permsSubmitLoading = ref(false);
const permissionTree = ref<MenuItem[]>([]);
const currentPermRoleId = ref<number | null>(null);
const permTreeRef = ref();

// 分页数据
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0
});

// 搜索表单
const searchForm = reactive({
  name: ""
});

// 表单数据
const formData = reactive<Partial<RoleItem>>({
  name: "",
  description: ""
});

// 表单验证规则
const formRules: FormRules = {
  name: [{ required: true, message: "请输入角色名称", trigger: "blur" }]
};

const formRef = ref<FormInstance>();

// 计算属性
const dialogTitle = computed(() => (isEdit.value ? "编辑角色" : "新增角色"));

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return "-";
  const date = new Date(dateString);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit"
  });
};

// 获取角色列表
const fetchRoleList = async () => {
  try {
    loading.value = true;
    const data = {
      page: pagination.page,
      limit: pagination.limit,
      ...(searchForm.name && { name: searchForm.name })
    };

    const response = await getRoleList(data);
    if (response.code === 0) {
      roleList.value = response.data.list;
      pagination.total = response.data.total;
    }
  } catch (error) {
    ElMessage.error("获取角色列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  fetchRoleList();
};

// 重置搜索
const handleReset = () => {
  searchForm.name = "";
  pagination.page = 1;
  fetchRoleList();
};

// 刷新
const handleRefresh = () => {
  fetchRoleList();
};

// 新增角色
const handleAdd = () => {
  isEdit.value = false;
  currentEditId.value = null;
  resetForm();
  dialogVisible.value = true;
};

// 编辑角色
const handleEdit = (row: RoleItem) => {
  isEdit.value = true;
  currentEditId.value = row.id!;
  Object.assign(formData, row);
  dialogVisible.value = true;
};

// 删除角色
const handleDelete = async (row: RoleItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${row.name}" 吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    await deleteRole(row.id!);
    ElMessage.success("删除成功");
    fetchRoleList();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: "",
    description: ""
  });
  formRef.value?.clearValidate();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    submitLoading.value = true;

    if (isEdit.value) {
      await updateRole(currentEditId.value!, formData);
      ElMessage.success("编辑成功");
    } else {
      await createRole(formData as Omit<RoleItem, "id" | "createTime">);
      ElMessage.success("新增成功");
    }

    dialogVisible.value = false;
    fetchRoleList();
  } catch (error) {
    ElMessage.error(isEdit.value ? "编辑失败" : "新增失败");
  } finally {
    submitLoading.value = false;
  }
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.limit = size;
  pagination.page = 1;
  fetchRoleList();
};

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page;
  fetchRoleList();
};

// 组件挂载时获取数据
onMounted(() => {
  fetchRoleList();
});

// 打开新增权限对话框
const openPermissionDialog = async (row: RoleItem) => {
  currentPermRoleId.value = row.id!;
  permsDialogVisible.value = true;
  await loadPermissionTree();
  await precheckRolePermissionsByNames();
};

// 加载权限树（从菜单接口获取）
const loadPermissionTree = async () => {
  try {
    permsLoading.value = true;
    const res = await getMenuTree();
    if (res.code === 0) {
      // 只展示目录/菜单/按钮均可，根据需要可过滤
      permissionTree.value = res.data || [];
    }
  } catch (error) {
    ElMessage.error("加载权限失败");
  } finally {
    permsLoading.value = false;
  }
};

// 预勾选（根据接口返回的权限名称）
const precheckRolePermissionsByNames = async () => {
  if (!currentPermRoleId.value) return;
  try {
    const res = await findPermissionByUserId(currentPermRoleId.value);
    if (res.code !== 0 || !Array.isArray(res.data) || res.data.length === 0)
      return;
    // 后端返回示例：["系统管理,用户管理,角色管理,菜单管理"]
    const names = res.data
      .flatMap(item => String(item).split(","))
      .map(s => s.trim())
      .filter(Boolean);

    // 根据名称在权限树中查找节点 id
    const idSet: number[] = [];
    const dfs = (nodes: any[]) => {
      nodes?.forEach(n => {
        if (names.includes(n.name)) idSet.push(n.id);
        if (n.children && n.children.length) dfs(n.children);
      });
    };
    dfs(permissionTree.value);

    requestAnimationFrame(() => {
      permTreeRef.value?.setCheckedKeys?.(idSet);
    });
  } catch (error) {
    // 忽略错误，仅不预选
  }
};

// 提交选中的权限
const submitPermissions = async () => {
  if (!currentPermRoleId.value) return;
  try {
    permsSubmitLoading.value = true;
    const checkedKeys: number[] = permTreeRef.value?.getCheckedKeys?.() || [];
    const payload: UpdateRolePermissionParams = {
      roleId: currentPermRoleId.value,
      permissionIds: checkedKeys
    };
    const res = await updateRolePermission(payload);
    if (res.code === 0) {
      ElMessage.success("权限更新成功");
      permsDialogVisible.value = false;
    } else {
      ElMessage.error(res.message || "权限更新失败");
    }
  } catch (error) {
    ElMessage.error("权限更新失败");
  } finally {
    permsSubmitLoading.value = false;
  }
};
</script>

<style scoped>
.main {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.content {
  padding: 20px 0;
}

.search-container {
  padding: 16px;
  margin-bottom: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

:deep(.el-table) {
  .el-table__row {
    .el-table__cell {
      padding: 8px 0;
    }
  }
}
</style>
